package akjvm.tools.java;

import akjvm.tools.java.classpath.Classpath;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * Created by VictoryWang on 2016/6/13.
 */
public class Cmd {

    @Parameter(names = {"-help", "-?"}, description = "print help message", help = true)
    private boolean help;

    @Parameter(names = {"-version"}, description = "print version and exit")
    private boolean version;

    @Parameter(names = {"-classpath", "-cp"}, description = "classpath")
    private String classpath;

    @Parameter(names = {"-Xjre"}, description = "path to jre")
    private String XjreOption;

    @Parameter
    private List<String> setupArgs;

    private String clazz;

    private JCommander commander = new JCommander(this);

    public void parseCmd(String[] args) {
        commander.parse(args);
        if (setupArgs != null && setupArgs.size() > 1) {
            clazz = setupArgs.get(0);
            setupArgs.remove(0);
        }
    }

    public static void main(String[] args) throws IOException {
        Cmd cmd = new Cmd();
        cmd.parseCmd(args);
        if (cmd.version) {
            JCommander.getConsole().println("akjvm java version 0.0.1");
        } else if (cmd.help || cmd.clazz == "") {
            cmd.commander.usage();
        } else {
            startJVM(cmd);
        }
    }

    private static void startJVM(Cmd cmd) throws IOException {
        JCommander.getConsole().println(String.format("classpath:%s class:%s args:%s", cmd.classpath, cmd.clazz, cmd.setupArgs));

        Classpath classpath = Classpath.parse(cmd.XjreOption, cmd.classpath);
        String className = cmd.clazz.replaceAll("\\.","/");
        System.out.println(Arrays.toString(classpath.readClass(className)));
    }
}
